import React, { useState, useEffect } from 'react';
import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  TextField,
  Box,
  Typography,
  Chip,
  IconButton,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  Grid,
  CircularProgress,
  Tooltip,
} from '@mui/material';
import { CloudUpload as CloudUploadIcon, Add as AddIcon, Image as ImageIcon } from '@mui/icons-material';
import { useResource } from '../ResourceContext';
import { useAuth } from '../../auth/AuthContext';
import { ResourceError, ResourceErrorType } from '../types';
import axios from 'axios';
import { getAuthHeaders } from '../../../config/apiConfig';

interface UploadResourceProps {
  open: boolean;
  onClose: () => void;
}

interface Tag {
  id: number;
  name: string;
}

interface TagSelection {
  id: number;
  name: string;
}

const UploadResource = ({ open, onClose }: UploadResourceProps) => {
  const [formData, setFormData] = useState({
    title: '',
    description: '',
    tags: [] as TagSelection[],
    torrentFile: null as File | null,
    coverImage: null as File | null,
  });
  const [availableTags, setAvailableTags] = useState<Tag[]>([]);
  const [selectedTag, setSelectedTag] = useState<number | ''>('');
  const [coverPreview, setCoverPreview] = useState<string>('');
  const [error, setError] = useState<ResourceError | null>(null);
  const [uploading, setUploading] = useState(false);
  const [loadingTags, setLoadingTags] = useState(false);
  const [generatingImage, setGeneratingImage] = useState(false);
  
  const { uploadResource } = useResource();
  const { user } = useAuth();

  // 获取所有可用标签
  useEffect(() => {
    const fetchTags = async () => {
      try {
        setLoadingTags(true);
        const response = await axios.get('/api/tag/tags', {
          headers: getAuthHeaders(),
          params: { page: 1, size: 50 }
        });
        setAvailableTags(response.data);
      } catch (err) {
        console.error('获取标签失败:', err);
        setError({
          type: ResourceErrorType.UNKNOWN_ERROR,
          message: '获取标签失败，请稍后重试'
        });
      } finally {
        setLoadingTags(false);
      }
    };

    if (open) {
      fetchTags();
    }
  }, [open]);

  const handleInputChange = (field: string, value: string) => {
    setFormData({ ...formData, [field]: value });
  };

  const handleAddTag = () => {
    if (selectedTag && !formData.tags.some(tag => tag.id === selectedTag)) {
      const tagToAdd = availableTags.find(tag => tag.id === selectedTag);
      if (tagToAdd) {
        setFormData({ ...formData, tags: [...formData.tags, { id: tagToAdd.id, name: tagToAdd.name }] });
        setSelectedTag('');
      }
    }
  };

  const handleRemoveTag = (tagIdToRemove: number) => {
    setFormData({
      ...formData,
      tags: formData.tags.filter(tag => tag.id !== tagIdToRemove),
    });
  };

  const handleTorrentFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    if (event.target.files && event.target.files[0]) {
      setFormData({ ...formData, torrentFile: event.target.files[0] });
    }
  };

  const handleCoverImageChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    if (event.target.files && event.target.files[0]) {
      const file = event.target.files[0];
      setFormData({ ...formData, coverImage: file });
      
      const reader = new FileReader();
      reader.onloadend = () => {
        setCoverPreview(reader.result as string);
      };
      reader.readAsDataURL(file);
    }
  };

  const handleSubmit = async () => {
    if (!formData.torrentFile || !user) {
      setError({
        type: ResourceErrorType.VALIDATION_ERROR,
        message: '请选择种子文件并确保已登录'
      });
      return;
    }

    if (!formData.title) {
      setError({
        type: ResourceErrorType.VALIDATION_ERROR,
        message: '请填写资源标题'
      });
      return;
    }

    try {
      setUploading(true);
      setError(null);

      // 上传资源
      const result = await uploadResource(formData.torrentFile, {
        title: formData.title,
        description: formData.description,
        tags: formData.tags,
        size: formData.torrentFile.size,
        uploaderId: user.id,
        uploaderName: user.username,
        coverImage: formData.coverImage,
      });

      console.log('上传成功:', result);
      
      // 重置表单
      setFormData({
        title: '',
        description: '',
        tags: [],
        torrentFile: null,
        coverImage: null,
      });
      setCoverPreview('');
      
      // 关闭对话框
      onClose();
    } catch (err) {
      console.error('上传失败:', err);
      if (err instanceof Error) {
        setError({
          type: ResourceErrorType.UPLOAD_FAILED,
          message: err.message
        });
      } else {
        setError({
          type: ResourceErrorType.UNKNOWN_ERROR,
          message: '上传失败，请稍后重试'
        });
      }
    } finally {
      setUploading(false);
    }
  };

  // 生成图片并下载
  const handleGenerateImage = async () => {
    try {
      setGeneratingImage(true);
      setError(null);
      
      // 使用资源标题作为生成提示，如果没有则使用默认值
      const prompt = formData.title || "篮球教学视频";
      
      // 调用Coze API生成图片
      const response = await axios.post('https://api.coze.cn/v1/workflow/run', {
        parameters: {
          input: prompt
        },
        workflow_id: "7515474657186005028"
      }, {
        headers: {
          'Authorization': 'Bearer pat_uJuk4SXCi2cbmtr5bpFmoQXod3K125IYrF6gcGYaXCUPE9zrQp6m0HIVKfELKBpr',
          'Content-Type': 'application/json'
        }
      });
      
      console.log('API响应:', response.data);
      
      // 解析返回的数据
      if (response.data && response.data.code === 0) {
        // 解析输出中的URL
        const outputData = JSON.parse(response.data.data);
        const imageUrl = outputData.output.trim();
        
        if (imageUrl) {
          // 下载图片
          const imageResponse = await axios.get(imageUrl, { responseType: 'blob' });
          const imageBlob = imageResponse.data;
          
          // 创建File对象
          const imageFile = new File([imageBlob], `generated_${Date.now()}.jpg`, { type: 'image/jpeg' });
          
          // 更新表单数据和预览
          setFormData({ ...formData, coverImage: imageFile });
          
          // 创建预览URL
          const reader = new FileReader();
          reader.onloadend = () => {
            setCoverPreview(reader.result as string);
          };
          reader.readAsDataURL(imageFile);
        } else {
          throw new Error('无法从API响应中获取图片URL');
        }
      } else {
        throw new Error(`API调用失败: ${response.data.msg || '未知错误'}`);
      }
    } catch (err) {
      console.error('生成图片失败:', err);
      setError({
        type: ResourceErrorType.UNKNOWN_ERROR,
        message: err instanceof Error ? err.message : '生成图片失败，请稍后重试'
      });
    } finally {
      setGeneratingImage(false);
    }
  };

  return (
    <Dialog open={open} onClose={onClose} maxWidth="md" fullWidth>
      <DialogTitle>上传资源</DialogTitle>
      <DialogContent>
        {error && (
          <Typography color="error" sx={{ mb: 2 }}>
            {error.message}
          </Typography>
        )}
        
        <Grid container spacing={3} sx={{ mt: 1 }}>
          <Grid item xs={12} md={8}>
            <TextField
              fullWidth
              label="资源标题"
              value={formData.title}
              onChange={(e) => handleInputChange('title', e.target.value)}
              margin="normal"
              required
            />

            <TextField
              fullWidth
              label="资源描述"
              multiline
              rows={4}
              value={formData.description}
              onChange={(e) => handleInputChange('description', e.target.value)}
              margin="normal"
              required
            />

            <Box sx={{ mt: 2 }}>
              <Typography variant="subtitle1" gutterBottom>标签</Typography>
              <Box sx={{ display: 'flex', alignItems: 'center', mb: 1 }}>
                <FormControl fullWidth size="small">
                  <InputLabel>选择标签</InputLabel>
                  <Select
                    value={selectedTag}
                    label="选择标签"
                    onChange={(e) => setSelectedTag(e.target.value as number)}
                    disabled={loadingTags}
                  >
                    {loadingTags ? (
                      <MenuItem disabled>加载中...</MenuItem>
                    ) : (
                      availableTags.map((tag) => (
                        <MenuItem key={tag.id} value={tag.id}>{tag.name}</MenuItem>
                      ))
                    )}
                  </Select>
                </FormControl>
                <IconButton onClick={handleAddTag} size="small" sx={{ ml: 1 }} disabled={!selectedTag}>
                  <AddIcon />
                </IconButton>
              </Box>
              <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 1 }}>
                {formData.tags.map((tag) => (
                  <Chip
                    key={tag.id}
                    label={tag.name}
                    onDelete={() => handleRemoveTag(tag.id)}
                    size="small"
                  />
                ))}
              </Box>
            </Box>
          </Grid>

          <Grid item xs={12} md={4}>
            <Box sx={{ mb: 3 }}>
              <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', mb: 1 }}>
                <Typography variant="subtitle1">封面图片</Typography>
                <Tooltip title="使用AI生成与资源标题相关的图片">
                  <Button
                    variant="contained"
                    color="primary"
                    size="small"
                    startIcon={<ImageIcon />}
                    onClick={handleGenerateImage}
                    disabled={generatingImage}
                    sx={{ ml: 1 }}
                  >
                    {generatingImage ? <CircularProgress size={24} /> : '生成图片'}
                  </Button>
                </Tooltip>
              </Box>
              
              <Box
                sx={{
                  width: '100%',
                  height: 200,
                  border: '2px dashed #ccc',
                  borderRadius: 1,
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  cursor: 'pointer',
                  overflow: 'hidden',
                  '&:hover': {
                    borderColor: 'primary.main',
                  },
                }}
                onClick={() => document.getElementById('cover-upload')?.click()}
              >
                {coverPreview ? (
                  <Box
                    component="img"
                    src={coverPreview}
                    sx={{
                      width: '100%',
                      height: '100%',
                      objectFit: 'cover',
                    }}
                  />
                ) : (
                  <Box sx={{ textAlign: 'center' }}>
                    <CloudUploadIcon sx={{ fontSize: 40, color: 'text.secondary' }} />
                    <Typography variant="body2" color="text.secondary">
                      点击上传封面
                    </Typography>
                  </Box>
                )}
                <input
                  type="file"
                  id="cover-upload"
                  hidden
                  accept="image/*"
                  onChange={handleCoverImageChange}
                />
              </Box>
            </Box>

            <Box>
              <Typography variant="subtitle1" gutterBottom>种子文件</Typography>
              <Box
                sx={{
                  width: '90%',
                  p: 2,
                  border: '2px dashed #ccc',
                  borderRadius: 1,
                  textAlign: 'center',
                  cursor: 'pointer',
                  '&:hover': {
                    borderColor: 'primary.main',
                  },
                }}
                onClick={() => document.getElementById('torrent-upload')?.click()}
              >
                <CloudUploadIcon sx={{ fontSize: 40, color: 'text.secondary' }} />
                <Typography variant="body2" color="text.secondary">
                  {formData.torrentFile ? formData.torrentFile.name : '点击上传种子文件'}
                </Typography>
                <input
                  type="file"
                  id="torrent-upload"
                  hidden
                  accept=".torrent"
                  onChange={handleTorrentFileChange}
                  required
                />
              </Box>
            </Box>
          </Grid>
        </Grid>
      </DialogContent>
      <DialogActions>
        <Button onClick={onClose}>取消</Button>
        <Button
          onClick={handleSubmit}
          variant="contained"
          disabled={uploading || !formData.title || !formData.torrentFile}
          startIcon={uploading ? <CircularProgress size={20} /> : undefined}
        >
          {uploading ? '上传中...' : '上传'}
        </Button>
      </DialogActions>
    </Dialog>
  );
};

export default UploadResource;